/*******************************************************************************
 * Copyright 2020 huanggefan.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package main

import (
	"context"
	"flag"
	"log"
	"net"
	"net/http"
	"runtime"
	"sync"
	"time"

	gRpcRuntime "github.com/grpc-ecosystem/grpc-gateway/runtime"
	"google.golang.org/grpc"

	"gitee.com/WisdomClassroom/collectingData/glb"
	"gitee.com/WisdomClassroom/collectingData/service"
	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

var (
	BuildTag  string
	BuildGo   string
	BuildTime string
)

func runGateway(wg *sync.WaitGroup) {
	defer wg.Done()

	headerMatcher := func(key string) (string, bool) {
		return key, true
	}

	gateway := gRpcRuntime.NewServeMux(
		gRpcRuntime.WithIncomingHeaderMatcher(headerMatcher),
		gRpcRuntime.WithMarshalerOption(
			gRpcRuntime.MIMEWildcard,
			&gRpcRuntime.JSONPb{OrigName: true, EmitDefaults: true},
		),
	)
	opts := []grpc.DialOption{grpc.WithInsecure()}
	err := pb.RegisterCollectingDataServiceHandlerFromEndpoint(context.Background(), gateway, core.FlagGRPCListen, opts)
	if err != nil {
		glb.Logger.Error(err.Error())
		return
	}

	mux := http.NewServeMux()
	mux.Handle("/api/", gateway)

	err = http.ListenAndServe(core.FlagHttpListen, mux)
	if err != nil {
		glb.Logger.Error(err.Error())
		return
	}
}

func runServer(wg *sync.WaitGroup) {
	defer wg.Done()

	listen, err := net.Listen("tcp", core.FlagGRPCListen)
	if err != nil {
		glb.Logger.Error(err.Error())
		return
	}

	grpcServer := grpc.NewServer()
	pb.RegisterCollectingDataServiceServer(grpcServer, &service.Service{})

	if err = grpcServer.Serve(listen); err != nil {
		glb.Logger.Error(err.Error())
		return
	}
}

func main() {
	core.PublicFlag(BuildTag, BuildGo, BuildTime)
	core.PublicServerFlag()
	mongoConnStr := flag.String("mongo-conn-str", "mongodb://localhost:27017", "MongoDB connection string.\n"+
		"eg. mongodb[+srv]://[<username>:<password>@]<cluster-address>")
	mongoDb := flag.String("mongo-db", "wisdom-classroom", "MongoDB Database")
	flag.Parse()

	if core.FlagHelp {
		flag.Usage()
		return
	}
	if core.FlagVersion {
		core.PublicVersion()
		return
	}

	if core.FlagLogWithUDP {
		addr, err := net.ResolveUDPAddr("udp", core.FlagLogAddr)
		if err != nil {
			log.Panicln(err)
		}
		glb.Logger, err = core.NewUDPLogger(core.FlagLogLevel, addr, 10240)
		if err != nil {
			log.Panicln(err)
		}
	} else {
		glb.Logger = core.NewLogger(core.FlagLogLevel)
	}

	if core.FlagPPROFEnable {
		go core.StartPPOFDebug(http.Server{Addr: core.FlagPPROFListen}, true)
		time.Sleep(1 * time.Second)
	}

	ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
	client, err := mongo.Connect(ctx, options.Client().ApplyURI(*mongoConnStr))
	if err != nil {
		glb.Logger.Error(err.Error())
		log.Panicln(err)
	}
	database := client.Database(*mongoDb)
	glb.ContentReadingCollection = database.Collection("content-reading")
	glb.AnswerCollection = database.Collection("answer")

	if core.FlagLogWithUDP {
		glb.Logger.Info("log to: udp://" + core.FlagLogAddr)
	}

	wg := new(sync.WaitGroup)
	wg.Add(2)
	go runGateway(wg)
	go runServer(wg)
	glb.Logger.Info("http listen at: http://" + core.FlagHttpListen)
	glb.Logger.Info("grpc listen at: grpc://" + core.FlagGRPCListen)
	wg.Wait()
}

func init() {
	runtime.GOMAXPROCS(1)
}
